package com.example.book_recommend.controller;

import com.example.book_recommend.pojo.User;
import com.example.book_recommend.pojo.VueLoginInfo;
import com.example.book_recommend.pojo.VueResultInfo;
import com.example.book_recommend.service.UserService;
import com.example.book_recommend.utils.ResultFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

@RestController
@EnableAutoConfiguration
@CrossOrigin
@RequestMapping("api")
public class UserController {
    @Autowired
    public UserService userService;

    /**
     * 登录控制器，前后端分离用的不同协议和端口，所以需要加入@CrossOrigin支持跨域。
     * 给VueLoginInfoVo对象加入@Valid注解，并在参数中加入BindingResult来获取错误信息。
     * 在逻辑处理中我们判断BindingResult知否含有错误信息，如果有错误信息，则直接返回错误信息。
     */
    @RequestMapping(value = "login", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public VueResultInfo userLogin(@RequestBody @Valid VueLoginInfo loginInfo, BindingResult bindingResult) throws IOException {
        VueResultInfo vueResultInfo = null;
        if (bindingResult.hasErrors()) {
            String message = String.format("参数错误，详细信息[%s]。", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
            vueResultInfo = ResultFactory.buildFailResult(message);
            return vueResultInfo;
        }

        User user = new User();
        user.setUsername(loginInfo.getUsername());
        user.setPassword(loginInfo.getPassword());
        System.out.println(bindingResult.hasErrors());
        user = userService.userLogin(user);

        if (user != null && Objects.equals(user.getPassword(),loginInfo.getPassword())) {
            vueResultInfo = ResultFactory.buildSuccessResult(user);
        } else {
            String message = "登陆失败，详细信息[用户名或密码错误]。";
            vueResultInfo = ResultFactory.buildFailResult(message);
        }
        return vueResultInfo;
    }


//    @RequestMapping(value = "login", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
//    public VueResultInfo getUserInfo(@RequestBody @Valid User user, BindingResult bindingResult){
//        VueResultInfo vueResultInfo;
//        if (bindingResult.hasErrors()) {
//            String message = String.format("参数错误，详细信息[%s]。", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
//            vueResultInfo = ResultFactory.buildFailResult(message);
//            return vueResultInfo;
//        }
//        vueResultInfo = ResultFactory.buildSuccessResult(user);
//        return
//    }

}

